/**
 * 
 */
package pt.mleiria.sAction.web.controller;


import java.util.Calendar;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import pt.mleiria.sAction.vo.UtilizadorVO;

/**
 * @author Manuel
 *
 */
public class MenuHandlerInterceptor extends HandlerInterceptorAdapter {

	protected final Logger logger = Logger.getLogger(this.getClass().getName());
	private long initTime;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//logger.info("INTERCEPT-->" + request.getRequestURI());
		initTime = Calendar.getInstance().getTimeInMillis();
		String destinationLink = request.getRequestURI();
		boolean result = false;
		try {
			UtilizadorVO utilizador = (UtilizadorVO) request.getSession()
					.getAttribute("utilizador");
			if (utilizador == null) {
				request.getSession().invalidate();
				response.sendRedirect("login.htm");
				result = false;
			} else {
				if (utilizador.isUserAuthorized(destinationLink)) {
					result = super.preHandle(request, response, handler);
				} else {
					response.sendRedirect("notAuthorized.htm");
					result = false;
				}
			}
		} catch (NullPointerException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
			request.getSession().invalidate();
			response.sendRedirect("login.htm");
			result = false;
		}
		return result;
	}
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		long elapsedTime = Calendar.getInstance().getTimeInMillis() - initTime;
		logger.info("TIME ELAPSED-->" + elapsedTime/1000 + " seconds");
		super.postHandle(request, response, handler, modelAndView);
	}
}
